package cn.est.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 本类提供了对URL所指向的内容的加载操作
 * @author hduser
 *
 */
public class UrlUtils {

	/**
	 * 获取url网址返回的数据内容
	 * @param urlStr
	 * @return
	 */
	//这个方法将字符串返回JSON对象
	public static String loadURL(String urlStr){
		try{  //封装url路径
	        URL url = new URL(urlStr);
	        //url.openConnection()获取连接   前提防火墙对这个请求开放
	        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();	              
	        urlConnection.setRequestMethod("GET");
		    urlConnection.connect();//获取到连接.connect()
			//getInputStream()获取输入流，输入流里有数据
		    InputStream inputStream = urlConnection.getInputStream();
		    //将这条输入流转换成response（响应字符串）
		    String responseStr = ConvertToString(inputStream);
		    //最后返回响应的字符串
		    return responseStr;
		}catch(IOException e){  
		    e.printStackTrace(); 
		    return null;
		}
	}
	//将输入流转换成字符串
	private static String ConvertToString(InputStream inputStream){
	    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
	    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
	    StringBuilder result = new StringBuilder();
	    String line = null;  
	    try {  
	        while((line = bufferedReader.readLine()) != null){  
	            result.append(line + "\n");  
	        }  
	    } catch (IOException e) {  
	        e.printStackTrace();  
	    } finally {  
	        try{  
	            inputStreamReader.close();  
	            inputStream.close();  
	            bufferedReader.close();  
	        }catch(IOException e){  
	            e.printStackTrace();  
	        }  
	    }  
	    return result.toString();  
	}  
}
